package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse reqs= (HttpServletResponse) response;
        String url=req.getRequestURL().toString();
        log.info("请求的url:{}",url);

        if(url.contains("login")){
            log.info("登录请求，放行");
            chain.doFilter(request,response);
            return;
        }

        String token = req.getHeader("token");
        if(!StringUtils.hasLength(token)){
            log.info("token为空，返回未登录的信息");
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            reqs.getWriter().write(s);
        }

        try {
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，返回未登录错误信息");
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            reqs.getWriter().write(s);
            return;
        }
        chain.doFilter(request,response);
    }
}
